package com.hfzy.ihk.web.freeswitchCall.controller;

import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.common.constants.GlobalStatic;
import com.hfzy.ihk.common.util.FileUtils;
import com.hfzy.ihk.common.util.date.DateUtils;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.web.freeswitchCall.biz.FreeswitchCallOutBiz;
import com.hfzy.ihk.web.freeswitchCall.constant.*;
import com.hfzy.ihk.web.freeswitchCall.context.EventSocketInitBean;
import com.hfzy.ihk.web.freeswitchCall.support.SampleMemoryCache;
import com.hfzy.ihk.web.freeswitchCall.support.SelectShowNumSupport;
import com.hfzy.ihk.web.freeswitchCall.vo.InterruptVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/9/1.
 *
 * @author wws
 */
@RestController
@RequestMapping("freeswitch")
public class FreeSwitchController {

    private  static final Logger logger=LoggerFactory.getLogger(FreeSwitchController.class);

    @Autowired
    EventSocketInitBean eslInitBean;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    FreeswitchCallOutBiz freeswitchCallOutBiz;

    @Autowired
    private SelectShowNumSupport selectShowNum;

    @RequestMapping("test")
    public String test(){
        return selectShowNum.getCopShowNum("1");

    }
    @RequestMapping("/channelLineMethod")
    public String channelLineMethod(String useReids){
        if("true".equals(useReids)){
            Constants.USE_REDIS_CHANNEL=true;
        }else{
            Constants.USE_REDIS_CHANNEL=false;
        }
        return "成功";

    }
    /*验证自己的号码是否存在或者注册*/
    @RequestMapping("/myPhoneNum")
    public Map<String,String> myPhoneNum(String result){

        Map<String,String> rs = new HashMap<>();

        rs.put("p",result);
        rs.put("code","1");
        rs.put("result","OK");

        return rs;
    }
    @RequestMapping("/youPhoneNum")
    public Map<String,String> youPhoneNum(String result){

        Map<String,String> rs = new HashMap<>();
        rs.put("p",result);
        rs.put("code","1");
        rs.put("result","OK");

        return rs;
    }
    @RequestMapping("/showPhoneStatus")
    public Map<String,String> showPhoneStatus(String result){

        Map<String,String> rs = new HashMap<>();
        rs.put("p",result);
        rs.put("code","1");
        rs.put("result","OK");
        return rs;
    }

    /**
     *
     * @param command:chananl uuid
     * @return
     */
    @RequestMapping("/killCallByNum")
    public Map<String,String> killCallByNum(String command){

        Map<String,String> result = new HashMap<>();

        result.put("p",command);
        result.put("code","1");
        result.put("result","OK");
        eslInitBean.getClient().sendBackgroundApiCommand("uuid_kill", " "+command );
        return result;
    }

    /**
     * freeswitch挂断操作
     * @param sessionId
     * @param autoInterrupt
     * @param jsonpCallBack
     * @return
     */
    @RequestMapping("/interruptCall")
    @ResponseBody
    public String interruptCall(String sessionId, boolean autoInterrupt, String jsonpCallBack){
        logger.debug("-----------interruptCall------------:" + sessionId + " isAuto:" + autoInterrupt);
        InterruptVo rsVo = new InterruptVo();
        if(StringTools.isEmpty(sessionId)||StringTools.isEmpty(autoInterrupt)){
            rsVo.setCode(-1);
            rsVo.setMsg("参数异常");
            if (StringUtil.isEmpty(jsonpCallBack))
                return JSONObject.toJSONString(rsVo).toString();

            return jsonpCallBack + "(" + JSONObject.toJSONString(rsVo).toString() + ")";
        }

        rsVo.setSessionId(sessionId);
        try {
            if (StringUtil.isEmpty(sessionId) || Constants.UN_DEFINED.equals(sessionId)) {
                rsVo.setCode(-1);
                rsVo.setMsg(Constants.LOCAL_EXCEPTION_7);
            } else {
                if (SampleMemoryCache.sessionInterruptMap.get(sessionId) != null
                        || redisTemplate.opsForValue().get(RedisKey.INTERRUPT_FAIL + sessionId) != null) { //防止重复操作

                    rsVo.setCode(-6);
                    rsVo.setMsg(Constants.LOCAL_MSG_DO_AGAIN);

                    if (StringUtil.isEmpty(jsonpCallBack))
                        return JSONObject.toJSONString(rsVo).toString();

                    return jsonpCallBack + "(" + JSONObject.toJSONString(rsVo).toString() + ")";
                }

                String redisSessionId = RedisKey.CALL_HISTORY_RPIX + sessionId;
                //中断操作记录入缓存
                if (autoInterrupt) { //自动中断 将操作保存到redis
                    redisTemplate.opsForHash().put(redisSessionId, RedisFields.INTERRUPT, Constants.AUTO_INTERRUPT.toString());
                } else { //手动中断
                    redisTemplate.opsForHash().put(redisSessionId, RedisFields.INTERRUPT, Constants.INTERRUPT.toString());
                }

                //中断时间
                redisTemplate.opsForHash().put(redisSessionId, RedisFields.INTERRUPTTIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
                /*读取当前状态*/
                Map<String, String> callHistoryMap = redisTemplate.opsForHash().entries(redisSessionId);
                String rs = null;
                if (autoInterrupt) { //自动中断
                    /*中断*/
                    rs = freeswitchCallOutBiz.todoInterruptCall(sessionId);
                    /*中断成功*/
                    if (Constants.SUCCESS.equals(rs)) {

                        rsVo.setCode(1);
                        rsVo.setMsg(Constants.LOCAL_MSG_CALL_OVER);
                        logger.debug("interruptCall clickCallStop SUCCESS: autoInterrupt");
                        redisTemplate.opsForValue().set(RedisKey.INTERRUPT_FAIL + sessionId, "true", RedisTimeOut.CACHE_FROUR_HOUR, TimeUnit.MILLISECONDS);
                    } else {
                    /*中断失败*/
                        rsVo.setCode(-2);
                        rsVo.setMsg(Constants.LOCAL_MSG_INTERRUPTE_FAILED);
                        logger.debug("interruptCall clickCallStop FAIL: 中断失败");
                    }

                } else {//手动挂断

                  /*运营商未返回状态，表明未开始呼叫，则需延迟中断到主叫ring状态返回时*/
                    /*中断*/
                    rs = freeswitchCallOutBiz.todoInterruptCall(sessionId);

                    if (Constants.SUCCESS.equals(rs))
                        redisTemplate.opsForValue().set(RedisKey.INTERRUPT_FAIL + sessionId, "true", RedisTimeOut.CACHE_FROUR_HOUR, TimeUnit.MILLISECONDS);

                     /*中断成功*/
                    if (Constants.SUCCESS.equals(rs)) {

                        /*正常通话，返回通话结束*/
                        rsVo.setCode(2);
                        rsVo.setMsg(Constants.LOCAL_MSG_CALL_OVER);
                        logger.debug("interruptCall clickCallStop SUCCESS: 手动");


                    } else {
                        /*中断失败*/
                        rsVo.setCode(-2);
                        rsVo.setMsg(Constants.LOCAL_MSG_INTERRUPTE_FAILED);
                        logger.debug("interruptCall clickCallStop SUCCESS: 中断失败:sessionId" + sessionId);
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("invoking interruptCall failed:" + e.getMessage());
            rsVo.setCode(-3);
            rsVo.setMsg(Constants.LOCAL_EXCEPTION_3);
        }

        logger.debug("SampleMemoryCache.sessionInterruptMap：sessionId=" + sessionId + SampleMemoryCache.sessionInterruptMap.get(sessionId));

        if (StringUtil.isEmpty(jsonpCallBack))
            return JSONObject.toJSONString(rsVo).toString();

        return jsonpCallBack + "(" + JSONObject.toJSONString(rsVo).toString() + ")";
    };

    @RequestMapping("/call")
    public Map<String,String> call(){

        //String uuid = UUID.randomUUID().toString();
        eslInitBean.getClient().sendBackgroundApiCommand( "bgapi originate", "{origination_caller_id_number=777,origination_caller_id_name=777,origination_uuid=00000001-0999}user/1005 &bridge({origination_caller_id_number=8888,origination_caller_id_name=8888}user/1000)" );
        //eslInitBean.getClient().sendSyncApiCommand( "bgapi originate", "{origination_caller_id_number=777,origination_caller_id_name=777,origination_uuid="+uuid+"}user/1004 &bridge({origination_caller_id_number=8888,origination_caller_id_name=8888}user/1020)" );
        Map<String,String> result = new HashMap<>();

        result.put("p","bgapi originate user/1005 &bridge(user/1000)");
        //result.put("p","bgapi originate user/1004 &bridge(user/1020)");
        result.put("code","1");
        result.put("result","OK");
        return result;
    }

    /**
     * 获取可以登录的用户
     * @return
     */
    @CrossOrigin(origins = "*") //跨域
    @RequestMapping("getUser")
    @ResponseBody
    public WebResult getUser(String callback){

        WebResult webResult=new WebResult();

        try {
            String user=freeswitchCallOutBiz.getUser();
            webResult.setTotal(1);
            webResult.setCode(GlobalStatic.SUCCESS);
            webResult.setMsg("随机获取用户正常");
            webResult.setParameter(user);
        }catch (Exception e){
            e.printStackTrace();
            logger.info("freeswitch log : 随机获取用户异常");
            webResult.setTotal(1);
            webResult.setCode(GlobalStatic.FAIL);
            webResult.setMsg("随机获取用户异常");
            Random random=new Random();
            webResult.setParameter("10"+random.nextInt(8)+2+random.nextInt(10));
        }

        return webResult;
    }
}
